package cn.com.oceansoft.business.os.api.qrcode.controller;

import cn.com.oceansoft.business.base.entity.Pager;
import cn.com.oceansoft.business.base.entity.Query;
import cn.com.oceansoft.business.base.entity.Result;
import cn.com.oceansoft.business.os.api.qrcode.domain.CheckIn;
import cn.com.oceansoft.business.os.api.qrcode.domain.User;
import cn.com.oceansoft.business.os.api.qrcode.service.IQrcodeService;
import cn.com.oceansoft.business.os.api.util.RequestUtils;
import cn.com.oceansoft.business.os.api.util.javaQRCode;
import cn.com.oceansoft.business.os.entity.Lucky;
import cn.com.oceansoft.business.os.service.ILuckyService;
import cn.com.oceansoft.nos.cache.redis.CacheBaseService;
import cn.com.oceansoft.nos.common.constant.Constant;
import cn.com.oceansoft.nos.common.util.MD5Util;
import cn.com.oceansoft.nos.common.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("api/qrcode")

public class QrcodeController {
    @Resource
    private CacheBaseService cacheBaseService;
    @Resource
    private IQrcodeService iQrcodeService;
    @Resource
    private ILuckyService luckyService;

    @RequestMapping(value = "gotoQrcode", method = RequestMethod.GET)
    public String gotoQrcode(HttpServletRequest request, ModelMap model) {
        String openId = (String) request.getSession().getAttribute("openId");
        if("ol7bHt68X2PmPbfSuSK6u7w356fM".equals(openId)||"ol7bHtyNqYn9wclH81YDX91OFM2o".equals(openId)){
            return "osyear/qrcode";
        }else{
            model.addAttribute("msg", "你没有权限哦！");
            return "errors/osyear_404";
        }
    }

    /**
     * 获取二维码base64
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getBase64", method = RequestMethod.GET)
    public JSONObject getEwm(HttpServletRequest request, HttpServletResponse response) {
        String imgPath = "";
        String timestamp = String.valueOf(System.currentTimeMillis());
        //   cacheBaseService.cache("hostopenId","sdjklsajdlajsd");//写入hostOpenId，只可以当前openId获取二维码图片
//                String hostOpenId = cacheBaseService.get("hostOpenId");//获取缓存
        String signature = MD5Util.KL(timestamp);
        String url = Constant.Qrcode_URL + signature;
        javaQRCode javaQRCode = new javaQRCode();
        String base64image = javaQRCode.encoderQRCodeBase64String(url, "png", 7);
        JSONObject json = new JSONObject();
        json.put("img", base64image);
        json.put("url", url);
        return json;
    }

    /**
     * 扫描后进入签到页面
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "gotoScan", method = RequestMethod.GET)
    public String gotoScan(HttpServletRequest request, ModelMap model) {
        //获取openId
        String openId = (String) request.getSession().getAttribute("openId");
        System.out.println("========>我的OPENID" + openId);
        //2.比对openId，签到过的人不进行校验，显示抽奖券
        boolean b = iQrcodeService.checkUserLogin(openId);
        if (!b) {
            CheckIn checkin = iQrcodeService.findCheckInByOpenId(openId);
            model.addAttribute("lotteryNumber", checkin.getLotteryNumber());
            return "osyear/ticket";
        }
        String signature = request.getParameter("signature");
        try {
            signature = MD5Util.JM(signature);
            String timestamp = String.valueOf(System.currentTimeMillis());
//            验证当前扫描二维码是否是最新状态
            if (Long.parseLong(timestamp) > Long.parseLong(signature) + 30000 && Long.parseLong(signature) <= Long.parseLong(timestamp)) {
                //TODO 404页面
                model.addAttribute("msg", "您的二维码已过期，请至现场重新扫描！");
                return "errors/osyear_404";
            }
        } catch (Exception e) {
            e.printStackTrace();
            //TODO 404页面
            model.addAttribute("msg", "出错！");
            return "errors/osyear_404";
        }
        return "osyear/checkin";
    }

    /**
     * 我的抽奖券
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "myAward", method = RequestMethod.GET)
    public String myAward(HttpServletRequest request, ModelMap model) {
        //获取openId
        String openId = (String) request.getSession().getAttribute("openId");
        if (StringUtils.isEmpty(openId)) {
            model.addAttribute("msg", "请至现场扫描二维码参加更多精彩活动！");
            return "errors/osyear_404";
        }
        CheckIn checkin = iQrcodeService.findCheckInByOpenId(openId);
        if (null == checkin || checkin.getId() == Integer.MIN_VALUE) {
            model.addAttribute("msg", "您尚未签到，请至现场扫描二维码,<br />参加更多精彩活动！");
            return "errors/osyear_404";
        } else {
            //获取我的抽奖券
            model.addAttribute("lotteryNumber", checkin.getLotteryNumber());
            return "osyear/ticket";
        }
    }

    /**
     * 用户签到
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public Result register(HttpServletRequest request, HttpServletResponse response) {
        //获取用户
        String openId = (String) request.getSession().getAttribute("openId");
        Map<String, String> param = new HashMap<String, String>();
        param = RequestUtils.buildParamsByNamesFromRequest(request);
        if (StringUtils.isEmpty(param.get("idcard"))) {
            return new Result(false, "缺失身份证号码！");
        }else{
            param.put("idcard",param.get("idcard").replace("x","X")) ;
        }
        if (StringUtils.isEmpty(param.get("name"))) {
            return new Result(false, "缺失姓名！");
        }
        //检查身份证号码和姓名是否对应
        User user = iQrcodeService.findUserByIdAndName(param);
        if (null == user) {
            return new Result(false, "身份信息错误，请核对！");
        } else {
            int i = iQrcodeService.checkIsCheckIn(user);
            if (i > 0) {
                return new Result(true, "您已签到，请勿重复操作！");
            }
            CheckIn checkIn = new CheckIn();
            checkIn.setLat(param.get("Lat"));
            checkIn.setLng(param.get("Lng"));
            checkIn.setLocation(param.get("Location"));
            checkIn.setOpenid(openId);
            checkIn.setUserid(user.getId());
            String LotteryNumbe = iQrcodeService.saveCheckIn(checkIn);
//            JSONObject json = new JSONObject();
//            json.put("LotteryNumbe",LotteryNumbe);
            return new Result(true, "签到成功");
        }
        //return null;
    }

    /**
     * 进入抽奖页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "gotoAward", method = RequestMethod.GET)
    public String gotoAward(HttpServletRequest request, ModelMap model) {
        Pager<Lucky> page =luckyService.findPageByCondition(new Query());
        model.addAttribute("lucky",page.getList());
        return "osyear/award";
    }

    /**
     * 获取中奖用户，券号
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAwardList", method = RequestMethod.POST)
    public Result getAwardList(HttpServletRequest request, HttpServletResponse response) {
        String awardid = request.getParameter("awardid");
        String votes = request.getParameter("votes");
        List<CheckIn> checkin = iQrcodeService.findtAwardList(awardid,votes);
        if(null!=checkin&&checkin.size()>0){
            //中奖人员保存到数据库
            for (int i = 0; i < checkin.size(); i++) {
//               iQrcodeService.saveAwardResult(String.valueOf(checkin.get(i).getUserid()), awardid);
            }
        }
        return new Result(true, checkin);
    }

    /**
     * 获取获奖人员名单
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "getAwardResult", method = RequestMethod.POST)
    public Result getAwardResult(HttpServletRequest request, HttpServletResponse response) {
        String awardid = request.getParameter("awardid");
        // List<User> userList = iQrcodeService.findtAwardList(awardid);
        //return new Result(true,userList);
        return null;
    }


    /**
     * 保存获奖人员
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "saveAwardResult", method = RequestMethod.POST)
    public Result saveAwardResult(HttpServletRequest request, HttpServletResponse response) {
        String userid = request.getParameter("userid");
        String awardid = request.getParameter("awardid");
        String[] userids = userid.split(",");
        for (int i = 0; i < userids.length; i++) {
            iQrcodeService.saveAwardResult(userids[i], awardid);
        }
        return new Result();
    }


}
